<?php
class Category extends CI_Controller{

	public function __construct(){
		parent::__construct();
		$this->load->model("category_model",'category');
	}
	
    //新加
	public function add(){
		$this->load->helper('form');
		$this->load->library("form_validation");
		$this->load->model("category_model");

		$data['title'] = "add a new item";
		$this->form_validation->set_rules('category_name', 'category_name', 'required');

  		if($this->form_validation->run() === false){
			$this->load->view('templates/header');
  			$this->load->view("admin/category/add");
			$this->load->view('templates/footer');
  		}else{
  			if($this->category->add()){
				$this->lists();
			}
  		}
		
	}

	//更新
	public function edit(){

		$this->load->helper('form','url');
		
		if(isset($_POST['action'])){
			if($_POST['action'] == 'update'){
				$data = array(
					'category_name' => $_POST['category_name'],
					'parent_id' => $_POST['parent_id'],
					'ordernum' => $_POST['ordernum']
				);

				$up = $this->category->edit($_POST['category_id'],$data);
				if($up){
					$this->load->view('admin/category/edit',array('result' => "修改成功"));
					
				}else{
					$data = array(
						'cate' => $this->article_model->getOneCate($_POST['id']),
						'result' => '更新失败或内容未发生变化!'
					);
					$this->load->view('templates/header');
					$this->load->view('admin/category/edit',$data);
					$this->load->view('templates/footer');
				}
			}
		}else{
			
			$id = $this->uri->segment(3);//取得id
			$data['cate'] = $this->category->getOneCate($id);
			$this->load->view('templates/header');
			$this->load->view('admin/category/edit',$data);
			$this->load->view('templates/footer');
		}

	}
	
	
		//删除
	public function delete(){
		$id = $this->uri->segment(3);
		if( $row = $this->category->delete($this->input->post('id')) ){
			$json['error'] = 0;
			$json['content'] = '';
			echo json_encode($json);
			return ;
		}else{
			$json['error'] = 1;
			$json['content'] = '删除失败!';
			echo json_encode($json);
			return ;
		}
	
	}
	//全部列出
	public function lists(){
       
		$data = array(
             "cates" => $this->category->getAllCategory2()
        );
			
		$this->load->view("templates/header");
		$this->load->view("admin/category/lists",$data);
		$this->load->view("templates/footer");
	}

		//更新状态
	public function status(){
		//文章状态更新
			
				$data = array(
					'status' => $_POST['status']
				);
				
				$where = array(
					'id' => $_POST['id']
				);
				
				
				$up = $this->category->up_status($where,$data);
				if($up){
					$json['error'] = 0;
					$json['content'] = $_POST['status'];
					echo json_encode($json);
					return ;
					
				}else{
					$json['error'] = 1;
					$json['content'] = $_POST['status'];
					echo json_encode($json);
					return ;
				}
			
			
	} 


}